import { createStore } from "vuex";

interface UserState {
  token: string | null;
  user: {
    username: string;
  } | null;
}

export default createStore({
  state: {
    token: localStorage.getItem("token") || null,
    user: JSON.parse(localStorage.getItem("user") || "null"),
  } as UserState,
  getters: {
    isAuthenticated: (state: UserState) => !!state.token,
    currentUser: (state: UserState) => state.user,
  },
  mutations: {
    SET_TOKEN(state: UserState, token: string) {
      state.token = token;
      localStorage.setItem("token", token);
    },

    SET_USER_INFO(state: UserState, user: { username: string }) {
      state.user = user;
      localStorage.setItem("user", JSON.stringify(user));
    },

    CLEAR_USER_INFO(state: UserState) {
      state.token = null;
      state.user = null;
      localStorage.removeItem("token");
      localStorage.removeItem("user");
    },
  },
  actions: {
    // 这里可以添加异步操作，比如登录、登出等
  },
  modules: {},
});
